<template>

  <el-tabs v-model="activeName" type="card" style="width: 100%"><!--@tab-click="handleClick"-->

    <el-row>
      <el-dialog title="供应商准入条例" :visible.sync="dialogFormVisible" :key="dialogKey" :modal="false">

        <div class="form-scroll-container">
          <el-form
                  :rules="formRules"
                  :model="supplierEnterRuleDTO"
                  ref="supplierEnterRuleDTO">
            <el-row style="color: #1a3bd7">
              <b>供应商准入条例</b>
              <el-progress :percentage="100" :show-text="false"></el-progress><!-- :format="format"--><!--水平线-->
            </el-row>

            <el-row :gutter="20" style="margin-top: 10px;">
              <el-col :span="20">
                1.本表数据作为《供应商准入》表中“选择准入条例”的数据源；<br>
                2.添加新数据后，新数据可以被《供应商准入》选用；
              </el-col>
            </el-row>

            <el-form-item prop="supplierEnterRule.name">
              <el-row :gutter="10" style="margin-top: 10px;">
                <el-col :span="5">
                  <b>条例名称</b>
                  <el-input
                          size="small" style="width: 300px;" clearable
                          v-model="supplierEnterRuleDTO.supplierEnterRule.name"></el-input>
                </el-col>
              </el-row>
            </el-form-item>

            <el-row :gutter="10" style="margin-top: 10px;"><b>准入条例</b></el-row>

            <el-form-item prop="supplierEnterRuleDataList">

              <el-table
                      :data="supplierEnterRuleDTO.supplierEnterRuleDataList"
                      style="width: 100%"
                      ref="supplierEnterRuleDataList">

                <el-table-column
                        prop="id"
                        label="序号"
                        width="50"
                        type="index"
                        align="center"
                        :index="(index) => index + 1"/>
                <el-table-column prop="rules" label="评估项" align="center">
                  <template #default="scope">
                    <span v-show="!scope.row.editFlag">{{ scope.row.rules }}</span>
                    <el-form-item
                            :prop="'supplierEnterRuleDataList.' + scope.$index + '.rules'"
                            :rules="formRules['rules']">
                      <el-input
                              size="small"
                              v-show="scope.row.editFlag"
                              v-model="scope.row.rules"
                              placeholder="评估项">
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column prop="maxScore" label="最高分" align="center">
                  <template #default="scope">
                    <span v-show="!scope.row.editFlag">{{ scope.row.maxScore }}</span>
                    <el-form-item
                            :prop="'supplierEnterRuleDataList.' + scope.$index + '.maxScore'"
                            :rules="formRules['maxScore']">
                      <el-input
                              type="number"
                              min="1"
                              max="100"
                              size="small"
                              v-show="scope.row.editFlag"
                              v-model="scope.row.maxScore"
                              placeholder="请输入最高分值">
                      </el-input>
                    </el-form-item>
                  </template>
                </el-table-column>
                <el-table-column label="操作" width="120" align="center">
                  <template #default="scope">
                    <div style="display: flex">
                      <el-button
                              size="small"
                              type="primary"
                              icon="CircleCheck"
                              style="width: 90px"
                              :key="scope.$index"
                              v-show="scope.row.editFlag"
                              @click="saveNewRule(scope)"
                      >保存
                      </el-button>
                      <el-button
                              size="small"
                              type="primary"
                              icon="CircleCheck"
                              style="width: 90px"
                              v-show="scope.row.editFlag"
                              @click="del(scope.row.$index)"
                      >删除
                      </el-button>
                      <el-button
                              size="small"
                              icon="Edit"
                              type="text"
                              v-show="!scope.row.editFlag"
                              @click="edit(scope.row)"
                      >修改
                      </el-button>
                      <el-button
                              size="small"
                              icon="Delete"
                              type="text"
                              v-show="!scope.row.editFlag"
                              @click="del(scope.$index)"
                      >删除
                      </el-button>
                    </div>
                  </template>
                </el-table-column>

              </el-table>
            </el-form-item>
            <div>
              <el-button
                      size="small" icon="el-icon-plus" @click="addRuleRow"
                      style="width: 100px; margin-top: 20px; background-color: #fff">添加
              </el-button>
              <el-button
                      size="small" icon="el-icon-document-copy" @click="pasteRow"
                      style="width: 100px; margin-top: 20px; background-color: #fff">粘贴新增
              </el-button>
            </div>
            <el-row :gutter="10" style="margin-top: 30px;">
              <el-col :span="5">
                <b>总分</b>
                <el-input
                        size="small" style="width: 300px;margin-top: 10px;"
                        v-model="supplierEnterRuleDTO.supplierEnterRule.totalScore"
                        readonly></el-input>
              </el-col>
            </el-row>
          </el-form>
        </div>

        <div slot="footer" class="dialog-footer">
          <el-button @click="resetForm">重 置</el-button>
          <el-button @click="dialogFormVisible=false">暂 存</el-button>
          <el-button type="primary" @click="submitMyForm('supplierEnterRuleDTO')">添 加</el-button>

        </div>
      </el-dialog>
    </el-row>

    <el-tab-pane label="全部数据" name="first">
      <el-table
              :data="supplierEnterRules"
              row-key="id"
              border
              @row-click="handleRowClick"
              :tree-props="{children: 'supplierEnterRuleDataList', hasChildren: 'hasChildren'}"
              @selection-change="handleSelectionChange">>

        style="width: 100%">
        <el-table-column label="选择条例" width="100">
          <template slot-scope="scope">
            <el-button @click="selectClause(scope.row)" type="text">选择</el-button>
          </template>
        </el-table-column>
        <el-table-column
                label="条例名称"
                prop="supplierEnterRule.name"
                width="180"
                :span-method="objectSpanMethod">
        </el-table-column>
        <el-table-column
                label="准入条则">
          <el-table-column
                  prop="rules"
                  label="评估项"
                  width="120">
            <template slot-scope="scope">
              <span @click="handleAssessmentItemClick(scope.row)">{{ scope.row.rules }}</span>
            </template>
          </el-table-column>
          <el-table-column
                  prop="maxScore"
                  label="最高分"
                  width="120">
          </el-table-column>
        </el-table-column>
        <el-table-column
                label="满分"
                prop="supplierEnterRule.totalScore"
                width="120">
        </el-table-column>
        <el-table-column
                label="提交人"
                prop="supplierEnterRule.createPerson"
                width="120">
        </el-table-column>
        <el-table-column
                label="提交时间"
                prop="supplierEnterRule.createTime"
                width="160">
          <template slot-scope="scope">
            <span>  {{
                scope.row.supplierEnterRule && scope.row.supplierEnterRule.createTime
                    ? $dayjs(scope.row.supplierEnterRule.createTime).format('YYYY-MM-DD HH:mm:ss') : ''
              }}</span>
          </template>
        </el-table-column>
        <el-table-column
                label="更新时间"
                prop="updateTime"
                width="160">
          <template slot-scope="scope">
            <!-- 使用 v-if 确保只有在 supplierEnterRule 存在且 updateTime 不为空时才显示 -->
            <span v-if="scope.row.supplierEnterRule && scope.row.supplierEnterRule.updateTime">
                {{ $dayjs(scope.row.supplierEnterRule.updateTime).format('YYYY-MM-DD HH:mm:ss') }}
              </span>
          </template>
        </el-table-column>
        <el-table-column
                prop=""
                label="">
        </el-table-column>

      </el-table>
    </el-tab-pane>
  </el-tabs>
</template>

<script>
  import index from "vuex";

  export default {
    name: "supplierEnterRuleBase",
    computed: {
      index() {
        return index
      }
    },
    //mzh添加
    props: {
      initialData: {
        type: Object,
        default: () => ({})
      }
    },
    data() {
      return {
        activeName: 'first',
        tableKey: 0, // 用于强制重新渲染表格
        dialogFormVisible: false,//添加准入规则dialog不显示
        dialogVisible: false, // 控制对话框显示/隐藏
        selectedRule: null, // 用来保存当前选中的条例信息
        ruleCounts: {}, // 辅助对象，用于存储每个条例的评估项数量
        dialogKey: 0,
        supplierEnterRules: [],//全部数据

        supplierEnterRuleDTO: {//dialog中的对象   准入条例
          supplierEnterRule: {
            name: "",
            totalScore: 0,//这项条例的总分，并不是每一小项的得分
            createPerson: "",
            createTime: "",
            updateTime: ""
          },
          supplierEnterRuleDataList: [],
        },
        multipleSelection: [],//批量删除
        formRules: {
          'supplierEnterRule.name': [
            {required: true, message: '请输入标题', trigger: 'blur'},
            {max: 10, message: "最多输入10个字符", trigger: "change"},
          ],
          'supplierEnterRuleDataList.*.rules': [
            {required: true, message: '请输入评估项名称', trigger: 'blur'}
          ],
          'supplierEnterRuleDataList.*.maxScore': [
            {required: true, message: '请输入1-100之间的数值!', trigger: 'blur'},
            {type: 'number', min: 1, max: 100, message: '请输入1-100之间的数值!', trigger: 'blur'}
          ]
        }
      };
    },
    methods: {
      /*mzh添加*/
      selectClause(supplierEnterRule) {
        // 触发一个事件，将选中的条例对象传递给父组件
        //console.log("Selecting clause:", supplierEnterRule);
        this.$emit('select-clause', supplierEnterRule);
        this.dialogFormVisible=false;
        this.dialogVisible=false;
      },
      handleRowClick(row) {
        // console.log(row.id)
        // // 设置 selectedRule 为当前行的 supplierEnterRule 数据
        this.selectedRule = row.supplierEnterRule;
        console.log(this.selectedRule)
        this.dialogVisible = true;
      },
      // 处理评估项点击事件
      handleAssessmentItemClick(assessmentItem) {
        const ruleId = assessmentItem.id; // 假设每个评估项都有一个 'id' 属性
        const foundRule = this.findRuleByAssessmentItemId(ruleId);

        if (foundRule) {
          console.log("找到的条例对象:", foundRule);
          console.log("评估项列表:", foundRule.supplierEnterRuleDataList);
          // 使用扩展运算符创建新的 selectedRule 对象
          this.selectedRule = {...foundRule};

          // 如果需要深拷贝，可以使用 JSON.parse(JSON.stringify) 或 lodash 的 cloneDeep
          this.selectedRule = JSON.parse(JSON.stringify(foundRule));

          this.dialogVisible = true;
        } else {
          console.log("未找到对应的条例对象");
        }
      },

      // 查找并返回包含指定评估项的条例对象
      findRuleByAssessmentItemId(ruleId) {
        for (let rule of this.supplierEnterRules) {
          if (rule.supplierEnterRuleDataList) {
            for (let item of rule.supplierEnterRuleDataList) {
              if (item.id === ruleId) {
                return rule;
              }
            }
          }
        }
        return null;
      },
      /*---------------------------------------------------------*/
      /*添加评估项按钮  添加新的一条评估项*/
      addRuleRow() {
        this.supplierEnterRuleDTO.supplierEnterRuleDataList.push({
          rules: '',
          maxScore: null,
          editFlag: true, // 可编辑标识
          isSubmit: false, // 是否点击确定标识
        });
      },
      /*粘贴评估项数据>>>>>>>>没实现*/
      pasteRow() {
        // const newRow = {
        //   index: this.supplierEnterRuleDTO.supplierEnterRuleDataList.length + 1,
        //   rules: '',
        //   maxScore: ''
        // };
        // this.supplierEnterRuleDTO.supplierEnterRuleDataList.push(newRow);
        // 粘贴新增功能未实现
        this.$message.warning('loading...');
      },
      /*保存新增的评估项按钮*/
      saveNewRule(scope) {
        const {$refs, $message} = this;
        const form = $refs.supplierEnterRuleDTO;

        // 定义要验证的字段
        const fieldsToValidate = [
          `supplierEnterRuleDataList.${scope.$index}.rules`,
          `supplierEnterRuleDataList.${scope.$index}.maxScore`
        ];

        // 使用 Promise.all 同时验证多个字段
        Promise.all(fieldsToValidate.map(field => new Promise((resolve) => {
          form.validateField(field, (errorMessage) => {
            resolve(errorMessage);
          });
        }))).then(errorMessages => {
          // 检查是否有任何验证错误
          if (errorMessages.some(message => message)) {
            // 如果有任意一个验证失败，则弹出第一个错误信息
            $message.error(errorMessages.find(message => message) || '未知错误');
          } else {
            // 额外的业务规则验证
            const validationErrors = this.checkBusinessRules(scope.row);

            if (validationErrors.length > 0) {
              // 如果有业务规则验证失败，只显示第一个错误信息
              $message.error(validationErrors[0]);
            } else {
              // 所有验证通过后的逻辑
              // console.log("所有验证通过");

              // 保存逻辑
              this.updateTotalScore();

              // 关闭编辑模式
              scope.row.editFlag = false;

              // 可选：显示成功消息
              $message({
                message: '保存成功',
                type: 'success'
              });
            }
          }
        }).catch(err => {
          console.error('验证过程中出现错误:', err);
          $message.error('保存过程中出现错误，请重试。');
        });
      },
      // 业务规则验证
      checkBusinessRules(row) {
        const errors = [];

        // 示例：检查评估项是否重复
        const duplicateRule = this.supplierEnterRuleDTO.supplierEnterRuleDataList.find(
                (item, index) => item.rules === row.rules && index !== this.supplierEnterRuleDTO.supplierEnterRuleDataList.indexOf(row)
        );
        if (duplicateRule) {
          errors.push('评估项名称不能重复');
        }

        // 示例：检查总分是否超出限制（假设总分不能超过100）
        const totalScore = this.supplierEnterRuleDTO.supplierEnterRuleDataList.reduce(
                (sum, item) => sum + (Number(item.maxScore) || 0), 0
        );
        if (totalScore > 100) {
          errors.push('总分不能超过100分');
        }

        // 添加其他业务规则验证...
        return errors;
      },

      /*删除条例*/
      del(index) {
        this.$confirm('此操作将永久删除该评估项, 是否继续?', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(() => {
          // 从数据列表中移除指定行
          this.supplierEnterRuleDTO.supplierEnterRuleDataList.splice(index, 1);
          //更新一下总分
          this.updateTotalScore();
          // 提示删除成功
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
        }).catch(() => {
          // 用户取消删除
          this.$message({
            type: 'info',
            message: '已取消删除'
          });
        });

        // 更新总分
        this.updateTotalScore();
      },
      /*编辑条例*/
      edit(row) {
        row.editFlag = true;
      },
      /*重置表单信息*/
      resetForm() {
        this.$refs.supplierEnterRuleDTO.resetFields();
        this.supplierEnterRuleDTO.supplierEnterRule.totalScore = null;
      },
      /*更新总分*/
      updateTotalScore() {
        let totalScore = 0;
        this.supplierEnterRuleDTO.supplierEnterRuleDataList.forEach(row => {
          if (row.maxScore && !isNaN(row.maxScore)) {
            totalScore += Number(row.maxScore);
          }
        });
        this.supplierEnterRuleDTO.supplierEnterRule.totalScore = totalScore;
      },
      /*----------------------------------------------------------------------------------------*/
      /*获取所有准入条例*/
      getRules() {
        this.$axios.get("manage/supplierEnterRule/list").then(response => {
          this.supplierEnterRules = response.data.data;
        });
      },
      /*提交按钮  提交添加的多条准入条例*/
      submitMyForm(formName) {
        console.log('提交的数据:', this.supplierEnterRuleDTO);  // 调试信息

        // 检查表单引用是否存在
        if (!this.$refs[formName]) {
          console.error('无法找到表单引用，请检查表单的 ref 属性');
          this.$message.error('表单引用无效，请重试');
          return;
        }

        // 检查 supplierEnterRuleDataList 是否为空
        if (this.supplierEnterRuleDTO.supplierEnterRuleDataList.length === 0) {
          this.$message.error('请添加至少一个评估项');
          return;
        }

        // 表单验证
        this.$refs[formName].validate((valid) => {
          if (valid) {
            // 检查是否有有效的评估项和得分
            const hasValidItems = this.supplierEnterRuleDTO.supplierEnterRuleDataList.some(item =>
                    item.rules && item.maxScore !== undefined && item.maxScore >= 1 && item.maxScore <= 100
            );

            if (!hasValidItems) {
              this.$message.error('请确保所有评估项都有有效的得分');
              return;
            }

            // // 动态计算总分
            // this.supplierEnterRuleDTO.supplierEnterRule.totalScore = this.supplierEnterRuleDTO.supplierEnterRuleDataList.reduce((sum, item) => {
            //   return sum + (item.maxScore || 0);
            // }, 0);
            this.updateTotalScore();
            // 提交数据
            this.$axios.post("manage/supplierEnterRule/add", this.supplierEnterRuleDTO)
                    .then(response => {
                      // 成功处理逻辑
                      this.$message({
                        message: '添加准入条例成功',
                        type: 'success'
                      });
                      // 关闭对话框
                      this.dialogFormVisible = false;
                    })
                    .catch(error => {
                      // 错误处理逻辑
                      console.error("提交失败:", error.response ? error.response.data : error);
                      this.$message.error('提交失败，请重试');
                    });
          } else {
            // 表单验证失败，显示汇总的错误信息
            this.$message.error('请检查各项是否填写正确');
            return false;
          }
        });
      },
      handleSelectionChange(val) {
        this.multipleSelection = val
      },
      /*批量删除*/
      handleDeleteBatch() {
        let ids = this.multipleSelection.map(supplierEnterRules => supplierEnterRules.id);
        if (ids.length > 0) {

          this.$confirm('此操作将永久删除该条例, 是否继续?', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
          }).then(() => {
            console.log("要删除的ids:" + ids)
            this.$axios.post("manage/supplierEnterRule/deleteBatch", ids).then(response => {
              this.dialogVisible = false;
              this.$message.success("删除成功")
              this.supplierEnterRules = this.supplierEnterRules.filter(supplierEnterRule => !ids.includes(supplierEnterRule.id))
            });
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消删除'
            });
          });


        } else {
          this.dialogVisible = false;
          this.$message.error("请选择要删除的条例")
        }


      },
      objectSpanMethod({row, column, rowIndex, columnIndex}) {
        return {
          rowspan: 5,
          colspan: 1
        }
      }
    },
    created() {
      this.getRules();
      let loginAdmin = JSON.parse(window.localStorage.getItem("form"))
      this.supplierEnterRuleDTO.supplierEnterRule.createPerson = loginAdmin.username
    }
  }
</script>

<style scoped>
  .form-scroll-container {
    max-height: 400px; /* 根据需要调整高度 */
    overflow-y: auto;
    padding: 10px; /* 可选，根据需要添加内边距 */
  //border: 1px solid #dcdfe6; /* 可选，根据需要添加边框 */
  //border-radius: 4px; /* 可选，根据需要添加圆角 */
  }
</style>